package com.wy.service.impl.wy;

import com.wy.bean.FeeBean;
import com.wy.bean.HouseBean;
import com.wy.dao.*;
import com.wy.model.sys.*;
import com.wy.service.wy.FeeService;
import com.wy.utils.DateUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("feeServiceImpl")
public class FeeServiceImpl implements FeeService {

	@Autowired
	private FeeRuleMapper feeRuleMapper;

	@Autowired
	private FeeRuleDimensionMapper feeRuleDimensionMapper;

	@Autowired
	private FeeRecordMapper feeRecordMapper;

	@Autowired
	private BuildingsMapper buildingsMapper;

	@Autowired
	private HousesMapper housesMapper;

	/**
	 * 新建费用规则
	 * @param feeBean
	 */
	@Override
	public void insertFeeRule(FeeBean feeBean) {
		feeRuleMapper.insertFeeBean(feeBean);
		if(null != feeBean.getFeeRuleDimensionList() && feeBean.getFeeRuleDimensionList().size() > 0) {
			List<FeeRuleDimension> list = new ArrayList<FeeRuleDimension>();
			for(FeeRuleDimension feeRuleDimension : feeBean.getFeeRuleDimensionList()) {
				feeRuleDimension.setFeeId(feeBean.getId());
				list.add(feeRuleDimension);
			}
			feeRuleDimensionMapper.insertBatch(list);
		}
	}

	/**
	 * 获取费用规则列表
	 * @param pageSize
	 * @param start
	 * @param residenceId
	 * @param feeName
	 * @param rids
	 * @return
	 */
	@Override
	public List<FeeBean> feeRuleList(Integer pageSize, Integer start, Integer residenceId, String feeName,String feeType, List<String> rids) {
		List<FeeBean> feeBeans = feeRuleMapper.feeRuleList(pageSize,start,residenceId,feeName,feeType,rids);
		for(FeeBean feeBean : feeBeans){
			feeBean.setFeeRuleDimensionList(feeRuleDimensionMapper.getFeeRuleDimensionByFeeId(feeBean.getId()));
		}
		return feeBeans;
	}

	/**
	 * 获取费用规则条数
	 * @param pageSize
	 * @param start
	 * @param residenceId
	 * @param feeName
	 * @param rids
	 * @return
	 */
	@Override
	public Integer feeRuleSize(Integer pageSize, Integer start, Integer residenceId, String feeName, String feeType,List<String> rids) {
		return feeRuleMapper.feeRuleSize(pageSize,start,residenceId,feeName,feeType,rids);
	}

	@Override
	public void updateFeeRule(FeeBean feeBean) {
		feeRuleMapper.updateByPrimaryKey(feeBean);
		feeRuleDimensionMapper.deleteByFeeId(feeBean.getId());
		if(null != feeBean.getFeeRuleDimensionList() && feeBean.getFeeRuleDimensionList().size() > 0) {
			List<FeeRuleDimension> list = new ArrayList<FeeRuleDimension>();
			for(FeeRuleDimension feeRuleDimension : feeBean.getFeeRuleDimensionList()) {
				feeRuleDimension.setFeeId(feeBean.getId());
				list.add(feeRuleDimension);
			}
			feeRuleDimensionMapper.insertBatch(list);
		}
	}

	@Override
	public void deleteFeeRule(List<String> groupId) {
		feeRuleMapper.deleteFeeRule(groupId);
		feeRuleDimensionMapper.deleteByGroupId(groupId);
	}


	/**
	 * 获取费用记录列表
	 * @param pageSize
	 * @param start
	 * @param residenceId
	 * @param feeName
	 * @param rids
	 * @return
	 */
	@Override
	public List<FeeRecord> feeRecordList(Integer pageSize, Integer start, Integer residenceId,String feeName,String feeStatus,String feeType,Integer houseId, List<String> rids,Integer buildingId) {
		return feeRecordMapper.feeRecordList(pageSize,start,residenceId,feeName,feeStatus,feeType,houseId,rids,buildingId);
	}

	/**
	 * 获取费用记录条数
	 * @param pageSize
	 * @param start
	 * @param residenceId
	 * @param feeName
	 * @param rids
	 * @return
	 */
	@Override
	public Integer feeRecordSize(Integer pageSize, Integer start, Integer residenceId,String feeName,String feeStatus,String feeType, Integer houseId, List<String> rids,Integer buildingId) {
		return feeRecordMapper.feeRecordSize(pageSize,start,residenceId,feeName,feeStatus,feeType,houseId,rids,buildingId);
	}

	@Override
	public List<FeeRecord> feeRecordList(String feeStatus, String feeType, Integer houseId) {
		return feeRecordMapper.feeRecordList4App(feeStatus,feeType,houseId);
	}

	@Override
	public void generateFeeRecord(Integer residenceId) {
		//1.查询需要生成的账单
		List<FeeBean> feeRules = feeRuleMapper.getFeeRuleByResidenceId(residenceId);

		if(null == feeRules || feeRules.size() == 0) {
			return;
		}
		//2.获取小区的房屋信息
		List<HouseBean> houses = housesMapper.getHousesByResidenceId(residenceId);
		if(null == houses || houses.size() == 0) {
			return;
		}

		//费用记录
		List<FeeRecord> feeRecords = new ArrayList<>();

		for(FeeBean rule : feeRules) {
			for(HouseBean houseBean : houses) {
				feeRecords.add(generateFeeRecordBySingalRule(rule,houseBean));
			}
		}

		//执行添加操作
		feeRecordMapper.insertBatch(feeRecords);
	}

	@Override
	public void generateFeeRecord(FeeBean feeBean) {
		//费用记录
		List<FeeRecord> feeRecords = new ArrayList<>();
		FeeRecord record = null;
		List<HouseBean> houses = housesMapper.getHousesByResidenceId(feeBean.getResidenceId());
		for(HouseBean houseBean : houses) {
			record = generateFeeRecordBySingalRule(feeBean,houseBean);
			if(null == record){
				continue;
			}
			feeRecords.add(record);
		}
		if(feeRecords.size() >0) {
			feeRecordMapper.insertBatch(feeRecords);
			feeRuleMapper.updateByPrimaryKeySelective(modifyFeeRuleNextTime(feeBean));
		}
	}

	@Override
	public List<FeeBean> getFeeRuleByTime(String today) {
		return feeRuleMapper.getFeeRuleByTime(today);
	}

	@Override
	public FeeBean getFeeRuleById(Integer id) {
		return feeRuleMapper.selectByPrimaryKey(id);
	}


	private FeeRecord generateFeeRecordBySingalRule(FeeBean rule,HouseBean houseBean) {
		//默认金额设置为0,根据规则来确定金额
		FeeRecord feeRecord = new FeeRecord(houseBean.getId(),rule.getId(),rule.getFeeName(),0.0,
				"0",null,null,"",new Date(),"admin",null);

		//如果周期为空，则表示为临时收费
		if(null == rule.getFeeCycle()) {
			feeRecord.setFeeAmount(rule.getFeeAmount());
		} else {
			//1.区分是按月固定，还是按年固定  xxxx费_2018.2-2018.3(1月收)
			String feeNameFormat = "%s_%s-%s(%s收)";
			String feeName = "";
			String feeStartTime = "";
			String feeEndTime = "";
			Integer feeCycle = 0;
			if(rule.getFeeCycle().contains("M")) {
				//根据执行时间，获取费用开始时间，结束时间
				feeCycle = new Integer(rule.getFeeCycle().replace("M",""));
				feeStartTime = DateUtils.getSpecifiedMonth(rule.getExt3(),0 - feeCycle).substring(0,4);
				feeEndTime = DateUtils.getTime(rule.getExt3(), DateUtils.timeformat4).substring(0,7);
				feeName = String.format(feeNameFormat,rule.getFeeName(),feeStartTime,feeEndTime,
						rule.getFeeCycle().replace("M","月"));

			}else if(rule.getFeeCycle().contains("Y")){
				//根据执行时间，获取费用开始时间，结束时间
				feeCycle = new Integer(rule.getFeeCycle().replace("Y",""));
				feeStartTime = DateUtils.getSpecifiedYear(rule.getExt3(),0 - feeCycle).substring(0,4);
				feeEndTime = DateUtils.getTime(rule.getExt3(),DateUtils.timeformat4).substring(0,4);
				feeName = String.format(feeNameFormat,rule.getFeeName(),feeStartTime,feeEndTime,
						rule.getFeeCycle().replace("Y","年"));
			}
			//公式为空则是固定收费，金额算法不同
			if(null == rule.getFeeFormula()) {
				//2.计算金额
				feeRecord.setFeeAmount(new BigDecimal(rule.getFeeAmount()).multiply(new BigDecimal(feeCycle)).setScale(2).doubleValue());
			} else {
				//2.计算金额
				//2.1 根据规则明细，确定单价
				Double unitFee = 0.0;  //单价
				String buildingLevel = houseBean.getBuildingLevel(); //当前房屋的类型
				String floor = houseBean.getFloor(); //当前房屋的楼层
				if(StringUtils.isEmpty(floor)) {
					//异常：楼层为空todo
					return null;
				}

				//首先拿楼栋类型和楼层来匹配，如果没有，就按照楼栋类，如果还没有，则不生成
				List<FeeRuleDimension> dimension = feeRuleDimensionMapper.getFeeRuleDimensionByCondition(rule.getId(),buildingLevel,floor);
				if(null == dimension || dimension.size() ==0 ){
					dimension = feeRuleDimensionMapper.getFeeRuleDimensionByCondition(rule.getId(),buildingLevel,null);
				}

				if(null == dimension || dimension.size() ==0 ){
					unitFee = rule.getExt4(); //当没有维度能匹配时，使用默认费用
				}else {
					unitFee = dimension.get(0).getFeeAmount1();
				}

				//判断公式类型：
				if(rule.getFeeFormula().equals("1")) {
					//1.需要乘以面积
					feeRecord.setFeeAmount(new BigDecimal(unitFee).multiply(new BigDecimal(houseBean.getHouseArea()))
							.multiply(new BigDecimal(feeCycle)).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue());
				}else if(rule.getFeeFormula().equals("2")) {
					//2.不需要乘以面积
					feeRecord.setFeeAmount(new BigDecimal(unitFee)
							.multiply(new BigDecimal(feeCycle)).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue());
				}
			}
			//3.设置账单名称（xxxx费_2018.2-2018.3(1月收)）
			feeRecord.setFeeName(feeName);
			feeRecord.setFeeStartTime(feeStartTime);
			feeRecord.setFeeEndTime(feeEndTime);
		}
		//规则执行记录
		//todo 记录日志

		return feeRecord;
	}

	/**
	 * 修改费用规则的下次执行时间
	 * @param rule
	 * @return
	 */
	private FeeBean modifyFeeRuleNextTime(FeeBean rule) {
		Integer feeCycle = 0;
		if(rule.getFeeCycle().contains("M")) {
			//根据执行时间，获取费用开始时间，结束时间
			feeCycle = new Integer(rule.getFeeCycle().replace("M",""));
			rule.setExt3(DateUtils.getSpecifiedMonth(rule.getExt3(),feeCycle));

		}else if(rule.getFeeCycle().contains("Y")){
			//根据执行时间，获取费用开始时间，结束时间
			feeCycle = new Integer(rule.getFeeCycle().replace("Y",""));
			rule.setExt3(DateUtils.getSpecifiedYear(rule.getExt3(),feeCycle));
		}
		return rule;
	}

	private boolean isBetween(String val,String section1,String section2) {
		boolean flag = false;
		try {
			if (new Integer(val) <= new Integer(section2) && new Integer(val) >= new Integer(section1)) {
				flag = true;
			}
		}catch(Exception ex) {
			flag = false;
		}
		return flag;
	}
}
